<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为三级分类设置相关联参数" type="warning" :closable='false' show-icon></el-alert>
      <el-row class='row'>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectList"
            :options="dataList"
            :props="cascader"
            @change="handleChange"
            clearable>
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="tabsActive" @tab-click="tabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type='primary' size='mini' :disabled='buttonActive' @click='buttonClick'>添加参数</el-button>
          <el-table :data='manyData' border striper >
            <el-table-column type='expand'>
              <template slot-scope='scope'>
                <el-tag closable v-for='(item,i) in scope.row.attr_vals' :key='i' @close='tagClose(i,scope.row)'>{{ item }}</el-tag>
                <el-input class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="newClick(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type='index'></el-table-column>
            <el-table-column label='参数名称' prop='attr_name'></el-table-column>
            <el-table-column label='操作' >
              <template slot-scope='scope'>
                <el-button type="primary" size='mini' icon="el-icon-edit" @click='showDia(scope.row)'>编辑</el-button>
                <el-button type="danger" size='mini' icon="el-icon-delete" @click='deleted(scope.row.attr_id)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type='primary' size='mini' :disabled='buttonActive' @click='buttonClick'>添加属性</el-button>
          <el-table :data='onlyData' border striper >
            <el-table-column type='expand'>
              <template slot-scope='scope'>
                <el-tag closable v-for='(item,i) in scope.row.attr_vals' :key='i' @close='tagClose(i,scope.row)'>{{ item }}</el-tag>
                <el-input class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="newClick(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type='index'></el-table-column>
            <el-table-column label='属性名称' prop='attr_name'></el-table-column>
            <el-table-column label='操作' >
              <template slot-scope='scope'>
                <el-button type="primary" size='mini' icon="el-icon-edit" @click='showDia(scope.row)'>编辑</el-button>
                <el-button type="danger" size='mini' icon="el-icon-delete" @click='deleted(scope.row.attr_id)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="'添加' + titletext" :visible.sync="DatadialogVisible" width="50%" @close='addclose'>
      <el-form :model="addForm" :rules="addFormrules" ref="ref_addForm" label-width="100px" class="demo-ruleForm">
        <el-form-item :label='titletext' prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DatadialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="'修改' + titletext" :visible.sync="editDia" width="50%" @close='editclose'>
      <el-form :model="editForm" :rules="editFormrules" ref="ref_editForm" label-width="100px" class="demo-ruleForm">
        <el-form-item :label='titletext' prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDia = false">取 消</el-button>
        <el-button type="primary" @click="editsubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    return {
      inputVisible:false,
      inputValue:'',
      editDia:false,
      addForm:{
        attr_name:'',
      },
      addFormrules:{
        attr_name:[
          { required:true, message:'请输入参数名称', trigger:'blur'}
        ]
      },
      editForm:{
        attr_id:'',
        attr_name:''
      },
      editFormrules:{
        attr_name:[
          { required:true, message:'请输入参数名称', trigger:'blur'}
        ]
      },
      DatadialogVisible:false,
      manyData:[],
      onlyData:[],
      tabsActive:'many',
      selectList:[],
      dataList:[],
      cascader:{ 
        expandTrigger: 'hover',
        value:'cat_id',
        label:'cat_name',
        children:'children'
      },
    }
  },
  computed:{
    buttonActive(){
      return this.selectList.length == 0
    },
    selectID(){
      if( this.selectList.length == 3 )
        return this.selectList[2]
      else {
        return null
      }
    },
    titletext(){
      if( this.tabsActive == 'many' ) return '动态参数'
      return '静态属性'
    }
  },
  methods:{
    async getData(){
      let res = await this.axios.get('/categories')
      if(res.data.meta.status == 200) {
        this.dataList = res.data.data
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    handleChange(){
      if( this.selectList.length != 3 ){
        this.manyData = []
        this.onlyData = []
        return this.selectList = []
      } 
      this.getItemData()
    },
    async getItemData(){
      let res = await this.axios.get(`/categories/${ this.selectID }/attributes`, {
        params:{ sel:this.tabsActive }
      })
      if(res.data.meta.status == 200) {
        res.data.data.forEach( item =>{
          if(item.attr_vals != '') {
            item.attr_vals = item.attr_vals.split(' ')
          } else item.attr_vals = []
          item.inputVisible = false
          item.inputValue = ''
        })
        if( this.tabsActive == 'many') {
          this.manyData = res.data.data
        } else {
          this.onlyData = res.data.data
        }
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    tabsClick() {
      if( this.selectList.length != 3 ){
        this.manyData = []
        this.onlyData = []
        return this.selectList = []
      } 
      this.getItemData()
    },
    buttonClick(){
      this.DatadialogVisible = true
    },
    addclose(){
      this.$refs.ref_addForm.resetFields()
    },
    addsubmit(){
      this.$refs.ref_addForm.validate(async vaild => {
        if(!vaild) return
        let res = await this.axios.post(`/categories/${ this.selectID }/attributes`, {
          attr_name:this.addForm.attr_name,
          attr_sel:this.tabsActive
        })
        if( res.data.meta.status == 201) {
          this.pop.success(res.data.meta.msg)
          this.getItemData()
          this.DatadialogVisible = false
        } else {
          this.pop.error(res.data.meta.msg)
        }
      })
    },
    async showDia(row){
      this.editDia = true
      let res = await this.axios.get(`categories/${ this.selectID }/attributes/${ row.attr_id }`,{
        params:{ attr_sel: this.tabsActive }
      })
      if(res.data.meta.status == 200) {
        this.editForm.attr_name = res.data.data.attr_name
        this.editForm.attr_id = res.data.data.attr_id
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    editsubmit(){
      this.$refs.ref_editForm.validate(async vaild => {
        if(!vaild) return
        let res = await this.axios.put(`/categories/${ this.selectID }/attributes/${ this.editForm.attr_id }`, {
          attr_name:this.editForm.attr_name,
          attr_sel:this.tabsActive
        })
        if( res.data.meta.status == 200) {
          this.pop.success(res.data.meta.msg)
          this.getItemData()
          this.editDia = false
        } else {
          this.pop.error(res.data.meta.msg)
        }
      })
    },
    editclose(){
      this.$refs.ref_editForm.resetFields()
    },
    async deleted(id){
      let res = await this.confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch( err=> {
        return err
      })
      if( res != 'confirm') return this.pop('取消删除')
      res = await this.axios.delete(`categories/${ this.selectID }/attributes/${ id }`)
      if( res.data.meta.status == 200) {
        this.pop.success(res.data.meta.msg)
        this.getItemData()
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    handleInputConfirm(row){
      if( row.inputValue.trim().length == 0 ) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      this.submitArrt(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    newClick(row){
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async submitArrt(row){
      let res = await this.axios.put(`categories/${ this.selectID }/attributes/${ row.attr_id }`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if( res.data.meta.status == 200 ){
        this.pop.success(res.data.meta.msg)
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    tagClose(i,row) {
      row.attr_vals.splice(i,1)
      this.submitArrt(row)
    }
  },
  created(){
    this.getData()
  }
}
</script>

<style lang='scss' scoped>
.el-breadcrumb {
  padding:15px 0;
}
.row {
  margin:15px 0;
}
.el-tag {
  margin:10px;
}
.input-new-tag {
  width:150px;
}
</style>
